import Router from "@koa/router";
import Joi from "joi";

export const routerManager = new Router();
routerManager.prefix("/api/v1");

// 路由注册的装饰器(类似java的注解)
export function router(params: Signal, _?: string) {
  return function (target: any, propertyKey: string) {
    let method = params.method || "post";
    const middlewares = target[propertyKey].__middlewares || [];
    if (target[propertyKey]._schema) middlewares.push(target[propertyKey]._schema);
    routerManager[method](params.url, ...middlewares, target[propertyKey]);
  };
}

// 路由加载中间件
export function middleware(...middlewares: Middleware[]) {
  return function (target: any, propertyKey: string) {
    target[propertyKey].__middlewares = middlewares;
  };
}

// 参数校验中间件
export function checkSchema<T = any>(schema: Joi.ObjectSchema<T>) {
  return function (target: any, propertyKey: string) {
    target[propertyKey]._schema = async function (c: Context, next: Next) {
      try {
        await schema.validateAsync(c.params);
      } catch (e) {
        console.log("参数校验:" + e);
        return c.fail("参数校验失败");
      }
      await next();
    };
  };
}
